package com.laixu.estore.web.controller;

import com.laixu.estore.bean.dto.UserLoginDTO;
import com.laixu.estore.bean.dto.UserRegisterDTO;
import com.laixu.estore.bean.vo.UserInfo;
import com.laixu.estore.bean.vo.UserLoginVo;
import com.laixu.estore.dao.UserDao;
import com.laixu.estore.service.UserService;
import com.laixu.estore.web.response.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("user")
@Slf4j // @Log4j
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;
    private final UserDao userDao;

    // 获取当前用户信息
    @GetMapping("getUserInfo")
    public Result getUserInfo(HttpServletRequest request) throws Exception {
        String id = (String) request.getAttribute("userId");
        // 3.通过id查出用户数据
        UserInfo userInfo = userService.getUserById(Integer.parseInt(id));
        return Result.success(userInfo);
    }

    @PostMapping("login")
    // @RequestBody 将json字符串 -》UserLoginDTO
    public Result login(@RequestBody UserLoginDTO userLoginDTO){ // Json: 账号密码
        log.info("登录: {}",userLoginDTO);
        //map: jwt userInfo{}
        //UserLoginVo: jwt userInfo
        UserLoginVo userLoginVo = userService.login(userLoginDTO);
        return Result.success(userLoginVo);
    }
    //注册
    @PostMapping("/register")
    public Result register(@RequestBody UserRegisterDTO userRegisterDTO) {
        String usename = userRegisterDTO.getUsername();
        String password = userRegisterDTO.getPassword();
        if (usename == null || password == null) {
            return Result.error(400, "用户名或密码不能为空");
        }
        if (userDao.login(usename, password) != null) {
            return Result.error(400, "用户名已存在");
        } else {
            userService.register(userRegisterDTO);
            return Result.success();
        }
    }

}